import { defineStore } from 'pinia'
import {  ref } from 'vue'
import * as userApi from "@/api/userApi";
import { ResponseCode } from '@/common/Responsetypes';

export interface IUserInfoStore {
  id: number;
  email: string;
  nickname: string;
  ext_data?: object;
}


export const useUserStore = defineStore('user', () => {

  const userInfo = ref<IUserInfoStore | null>(null)

  async function login(data: object) {
    const result = await userApi.login(data)
    if (result.code === ResponseCode.PASS) {
      userInfo.value = result.data;
    }
    return result
  }

  async function whoami() {
    const result = await userApi.whoami()
    if (result.code === ResponseCode.PASS) {
      userInfo.value = result.data;
    }
    return result
  }

  async function register(data: object) {
    const result = await userApi.register(data)
    if (result.code === ResponseCode.PASS) {
      userInfo.value = result.data;
    }
    return result
  }

  async function logout() {
    userInfo.value = null
  }

  return {
    userInfo,
    login,
    whoami,
    register,
    logout
  }
})